package com.juyueange.user;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/***
 * By Carl.lee
 * Time 2017-05-02
 */
public class PayActivity extends Activity implements OnClickListener {
    private Button submitButton;
    private Button confirmButton;
    private TextView tv_content;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;
    private PayReq req;
    private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        submitButton = (Button) findViewById(R.id.bt_submit_order);
        confirmButton = (Button) findViewById(R.id.bt_corfirm);
        tv_content = (TextView) findViewById(R.id.tv_prepay_id);
        submitButton.setOnClickListener(this);
        confirmButton.setOnClickListener(this);
        sb = new StringBuffer();
        req = new PayReq();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.bt_submit_order:
                String urlString = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                PrePayIdAsyncTask prePayIdAsyncTask = new PrePayIdAsyncTask();
                prePayIdAsyncTask.execute(urlString);      //生成prepayId
                break;
            case R.id.bt_corfirm:
                genPayReq();//生成签名参数
                break;
            default:
                break;
        }



    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private void genPayReq() {
//        req.appId = Constants.APP_ID;
//        req.partnerId = Constants.MCH_ID;
//        req.packageValue = Constants.PACKAGE;
//        if (resultunifiedorder != null) {
//            req.prepayId = resultunifiedorder.get("prepay_id");
//        } else {
//            Toast.makeText(PayActivity.this, "prepayid为空", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        req.nonceStr = getNonceStr();
//        req.timeStamp = String.valueOf(genTimeStamp());
//        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
//        signParams.add(new BasicNameValuePair("appid", req.appId));
//        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
//        signParams.add(new BasicNameValuePair("package", req.packageValue));
//        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
//        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
//        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//
//        req.sign = genAppSign(signParams);
        req.appId = Constants.APP_ID;
        req.partnerId = Constants.MCH_ID;
        req.packageValue = Constants.PACKAGE;
        req.sign ="B0D4789A6949D4F72BBDF390B637A773";
        req.timeStamp = "1525944668";
        req.prepayId = "wx10173107100728fd1b6feb2a0304262634";
        req.nonceStr = "67038aaa05ffac51830cffb04441f8c3";
        msgApi.registerApp(Constants.APP_ID);
        boolean isChat = msgApi.sendReq(req);
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);
        String appSign = MD5.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        tv_content.setText("sign str\n" + sb.toString() + "\n\n");
        return appSign;

    }

    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    private class PrePayIdAsyncTask extends AsyncTask<String, Void, Map<String, String>> {
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = ProgressDialog.show(PayActivity.this, "提示", "正在提交订单");
        }

        @Override
        protected Map<String, String> doInBackground(String... params) {
            String url = String.format(params[0]);
            String entity = getProductArgs();
            byte[] buf = Util.httpPost(url, entity);
            String content = new String(buf);
            Map<String, String> xml = decodeXml(content);
            return xml;
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            super.onPostExecute(result);
            if (dialog != null) {
                dialog.dismiss();
            }
            tv_content.setText(result.toString());
            resultunifiedorder = result;
        }
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("PayDemo", "----" + e.toString());
        }
        return null;
    }

    private String getProductArgs() {
        try {
            String nonceStr = getNonceStr();
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", Constants.APP_ID));
            packageParams.add(new BasicNameValuePair("attach", "xxxx"));
            packageParams.add(new BasicNameValuePair("body", "test_goods_name"));
            packageParams.add(new BasicNameValuePair("device_info", "android"));
            packageParams.add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Constants.NOTIFY_URL));
            packageParams.add(new BasicNameValuePair("out_trade_no", genOutTradNo()));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", "10.95.204.151"));
            packageParams.add(new BasicNameValuePair("total_fee", "1"));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));
            String sign = getPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));
            String xmlString = toXml(packageParams);
            return xmlString;
        } catch (Exception e) {
            return null;
        }
    }

    //生成订单号,测试用，在客户端生成
    private String genOutTradNo() {
        return new Date().getTime() + "";
    }

    //生成签名
    private String getPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);
        String packageSign = MD5.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return packageSign;
    }

    //生成随机号，防重发
    private String getNonceStr() {
        Random random = new Random();
        return MD5.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
    }

    //转换成xml
    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");
            sb.append("<![CDATA[" + params.get(i).getValue() + "]]>");
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");
        Log.e("PayDemo", "toxml :  " + sb.toString());
        return sb.toString();
    }
}